// ==UserScript==
// @name           Help Forum Reference Box Replacer
// @namespace      HF
// @description    Changes the reference box in Help Forums with one relying on Goole AJAX Search API
// @include        http://www.google.com/support/forum/*
// @include        http://*.briefer.net/*
// ==/UserScript==

var u2uKB = 'goog.briefer.net';

var log = (unsafeWindow.console) ? unsafeWindow.console.log : GM_log;
var currentURL = document.location.href.toString();
var shortCache = new Array();
GM_setValue('resCount',0);

var c = '\
	<div id="searchForm"> \
	<form class="gsc-search-box" accept-charset="utf-8" name="doSearch"> \
		<table cellspacing="0" cellpadding="0" class="gsc-search-box"> \
			<tbody> \
				<tr> \
					<td class="gsc-input"> \
						<input type="text" size="10" class=" gsc-input" name="search" title="search" id="fsq"> \
					</td> \
					<td class="gsc-search-button"> \
						<input type="submit" value="Search" class="gsc-search-button" title="search"> \
					</td> \
					<td class="gsc-clear-button"> \
						<div class="gsc-clear-button" > \
							<a name="rs" class="gsc-clear-button" title="clear results" style="display:inline-block;width:100%;">&nbsp;</a></div> \
					</td> \
				</tr> \
			</tbody> \
		</table> \
			<table cellspacing="0" cellpadding="0" class="gsc-branding" style="width:100%"> \
				<tbody> \
					<tr> \
						<td class="gsc-branding-user-defined"></td> \
						<td class="gsc-branding-text"> \
							<div class="gsc-branding-text">powered by</div> \
						</td> \
						<td class="gsc-branding-img"> \
							<img src="http://www.google.com/uds/css/small-logo.png" class="gsc-branding-img"> \
						</td> \
					</tr> \
				</tbody> \
			</table> \
		</form> \
	</div>\
    <div id="se_res"></div> \
	<span id="searcher_store_searcher" style="display:none"></span> \
	<span id="searcher_store_res" style="display:none">0</span>';
var d = '<div class="gsc-control"> \
			<div class="gsc-tabsArea"> \
				<div class="gsc-tabHeader gsc-tabhActive" id="searchS_web-hc" name="ds_web-hc"> \
					<a href="#" name="ds_web-hc" class="noAnchor">Help Center</a> \
				</div> \
					<span class="gs-spacer"> </span> \
				<div class="gsc-tabHeader gsc-tabhInactive" id="searchS_web-fo" name="ds_web-fo"> \
					<a href="#" name="ds_web-fo" class="noAnchor">This Forum</a> \
				</div> \
					<span class="gs-spacer"> </span> \
				<div class="gsc-tabHeader gsc-tabhInactive" id="searchS_web-u2u" name="ds_web-u2u"> \
					<a href="#" name="ds_web-u2u" class="noAnchor">U2U Content</a> \
				</div> \
				<div class="gsc-tabHeader gsc-tabhInactive" id="searchS_web" name="ds_web"> \
					<a href="#" name="ds_web" class="noAnchor">Web</a> \
				</div> \
					<span class="gs-spacer"> </span> \
				</div> \
			<div class="gsc-resultsbox-visible"> \
				<div class="gsc-resultsRoot gsc-tabData gsc-tabdActive"> \
					<div class="gsc-results gsc-webResult" style="display: block;"> \
						<div class="gsc-webResult gsc-result"> \
							<div class="gs-webResult gs-result" id="GM-sres">Loading results...</div> \
						</div> \
					</div> \
				</div> \
			</div> \
		</div>';
var css= '#utilities{padding:4px;width:500px}.gsc-input{width:400px}.wssmsicCSS{border:0 none!important;}.gsc-control{width:440px!important}.noAnchor{text-decoration:none;color:#333!important}';
var ThreadView = {
	get: function(el) {
		if (typeof el === 'string') {
			var ret_s = document.getElementById(el);
			return ret_s;
		} else {
			return el;
		}
	},
	add: function(content) {
		var GM_Head = document.getElementsByTagName('head')[0] || document.documentElement,
		GM_style1 = document.createElement('style');
		GM_style1.type = 'text/css';
		GM_style1.innerHTML = '@import url("http://www.google.com/uds/api/search/1.0/9e851088de4ceeea5a080c46a04c2720/default.css");';
		GM_style2 = document.createElement('style');
		GM_style2.type = 'text/css';
		GM_style2.innerHTML = css;
        GM_Head.insertBefore(GM_style1, GM_Head.firstChild);
		GM_Head.insertBefore(GM_style2, GM_Head.firstChild);

		nE = document.createElement('div');
		nE.id = "utilities";
		nE.innerHTML = content;
    	document.getElementById("wssmrt").appendChild(nE);
		document.getElementById("wssmrt").style.display= "block";
	},
	remove: function(el) {
		var el = this.get(el);
		el.parentNode.removeChild(el);
	},
	getForumName: function() {
		var currentUrl = document.location.href.toString();
		var groupName = currentUrl.match("/forum\/p\/([^/]*)[/\?]")[1];
    	return groupName
	},
	getForumLanguage: function() {
		var currentUrl = document.location.href.toString();
		var languageCode;
		// Pistachio
		languageCodes = currentUrl.match("[\?&]hl=([^&]*)");
		if (languageCodes) {
			languageCode = languageCodes[1];
		}else{
			languageCode = "en";
		}
		return languageCode
	},
	injectRef: function(a) {
		var postArea = window.frames[0].document;
		var postAreaBody = postArea.getElementsByTagName("body")[0];
		postAreaBody.innerHTML += a;
		postAreaBody.focus();
  	},
	jsinArray: function(a, b) {
    	var l = b.length;
	    for(var i = 0; i < l; i++) {
    	    if(b[i] == a) return true;
	    }
    	return false;
	},
	searcher: function(type, query){
		var forum = ThreadView.getForumName();
		var lang = ThreadView.getForumLanguage();
		query = escape(query);
		furl = 'http://u2u-ghf-helper.appspot.com/u2u_ghf_helper?service='+type+'&q='+query+'&hl='+lang+'&forum='+forum+'&u2u='+u2uKB+'&kb='+Math.floor(Math.random()*121);
		GM_xmlhttpRequest({
			method: "GET",
			url: furl,
			onload: function(response) {
				var content = response.responseText;
				res = JSON.parse(content, function (key, value) {
										var type;
										if (value && typeof value === 'object') {
											type = value.type;
											if (typeof type === 'string' && typeof window[type] === 'function') {
												return new (window[type])(value);
											}
										}
										return value;
								});
				ThreadView.renderResults(res, type);
				var oldTab_val = document.getElementById('searcher_store_searcher').innerHTML;
				var newTab = document.getElementById('searchS_' + type);
				var oldTab = document.getElementById('searchS_' + oldTab_val);
				oldTab.className= 'gsc-tabHeader gsc-tabhInactive';
				newTab.className= 'gsc-tabHeader gsc-tabhActive';
				document.getElementById('searcher_store_searcher').innerHTML = type;
			}
		});

	},
	renderResults: function(a, b){
		document.getElementById('se_res').innerHTML = d;
		var container = document.getElementById('GM-sres');
		var results = a.responseData.results;
		var ccount = GM_getValue('resCount');
		var resp = '';
		if(results.length == 0){resp += '<br />No results found. Please refine your search'}
		for (var j=0;j<results.length; j++) {
			var adder, adder2 = '';
			var data = escape(results[j].title +' - '+ results[j].unescapedUrl);
			if(ThreadView.jsinArray(data,shortCache) === true){
				adder = '<span id="'+data+'">Added...</span>';
			}else{
				adder = '<span id="'+data+'"><input type="button" value="Add" name="st_'+data+'" /></span>';
			}
			if(b== 'web-fo'){
				adder2 = '<div class="gs-visibleUrl gs-visibleUrl-short" style="text-align:right; color:red; font-weight:bold"> \
				<label>Mark as duplicate <input type="checkbox" value="'+results[j].unescapedUrl+'" name="dup_tid" onclick="CALL(\'cf.sourceEditModule.markDuplicate\', this);" class="wesmmdi" id="jsuid'+ccount+'_isDuplicate"></label> \
				</div>';
			}
			resp += '<div class="gs-webResult gs-result" style="margin-top:10px;"> \
				<div style="float:left; width:60px; height:50px; padding-top:20px;">'+adder+'</div> \
				<div style="float:left:width:370px; clear:right;"> \
										\
				<div class="gs-title"> \
					<a class="gs-title" href="' + results[j].unescapedUrl +'" target="_blank">'+results[j].title+'</a> \
				</div> \
				<div class="gs-snippet">'+results[j].content+'</div> \
				<div class="gs-visibleUrl gs-visibleUrl-short">'+results[j].visibleUrl+'</div> \
				<div class="gs-visibleUrl gs-visibleUrl-long">'+results[j].unescapedUrl+'</div> \
				'+adder2+' \
						\
				</div> \
			</div>';
		}
		document.getElementById('GM-sres').innerHTML = resp;
	},
	removeResults: function(){
		document.getElementById('se_res').innerHTML = ''
		document.getElementById('fsq').value = ''
	},
	listen: function(){
		document.addEventListener('submit',function(event){
			var eventName;
			try { eventName = event.target.name;} catch(ex) { }
			if (eventName) {
				if(eventName == 'doSearch'){
					var query = document.getElementById('fsq').value;
					document.getElementById('searcher_store_searcher').innerHTML = 'web-hc';
					ThreadView.searcher('web-hc',query);
					event.stopPropagation();
					event.preventDefault();
				}
			}
		},true);
		document.addEventListener('click', function(event) {
			var en;
			try { en = event.target.name;} catch(ex) { alert(ex)}
			if (en) {
				if(en == 'rs'){
					ThreadView.removeResults();
					event.stopPropagation();
					event.preventDefault();
				} else if (en.toString().substr(0,3) == 'ds_' ) {
					var tabId = en.toString().substr(3);
					var query = document.getElementById('fsq').value;
					ThreadView.searcher(tabId,query);
					event.stopPropagation();
					event.preventDefault();
				} else if (en.toString().substr(0,3) == 'st_' ) {
					var content = en.toString().substr(3);
					shortCache.push(content);
					document.getElementById(content).innerHTML = 'Added...';
					var count = GM_getValue('resCount');
					if(count == 0){
						var pre = '<br/><br/><br/><b>References:</b><br/><br/>';
						c = '1';
						content = pre+'['+c+']  '+content+'<br />';
						GM_setValue('resCount',2);
					}else{
						content = '['+count+']  '+content+'<br />';
						var inc = parseInt(count) + 1;
						GM_setValue('resCount',inc);
					}
					ThreadView.injectRef(unescape(content));
					event.stopPropagation();
					event.preventDefault();
				}
			}
		}, true);
	},
	doitall: function(){
		 ThreadView.remove('wssmfm');
		 ThreadView.add(c);
		 ThreadView.listen();
	}	
}

if (currentURL.match(/\/www\.google\.com\/support\/forum\//i)) {
  if (currentURL.match(/\/thread\?/i)) {
    if (document.getElementById("wmfroot")) {
      ThreadView.doitall();
	}
  }
}